﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using DALS = Medianamik.Core.DAL.SubSonicDAL;

namespace Medianamik.Core.DAL.Repositories
{
    internal class MedianamikControlRepository : IMedianamikControlRepository 
    {
        private readonly IDataTypeRepository _dataTypeRepository;

        public MedianamikControlRepository(IDataTypeRepository dataTypeRepository)
        {
            _dataTypeRepository = dataTypeRepository;
        }

        public MedianamikControl Get(Guid id)
        {
            var webControl = new SubSonicDAL.MedianamikControl(id);

            return AdaptFrom(webControl);
        }

        public IEnumerable<MedianamikControl> Get(Guid? pDataTypeId, MedianamikControlType? pControlType)
        {
            var DALcol = new SubSonicDAL.MedianamikControlCollection();

            if (pControlType.HasValue)
            {
                DALcol.Where(SubSonicDAL.MedianamikControl.Columns.Type, (byte)pControlType.Value);
            }

            if (pDataTypeId.HasValue)
            {
                DALcol.Where(SubSonicDAL.MedianamikControl.Columns.DataTypeID, pDataTypeId);
            }

            DALcol.OrderByAsc(SubSonicDAL.MedianamikControl.Columns.Name);

            DALcol.Load();

            return DALcol.Select(c=>AdaptFrom(c));
        }

        private MedianamikControl AdaptFrom(DALS.MedianamikControl pDALMedianamikControl)
        {
            var datatype = _dataTypeRepository.Get(pDALMedianamikControl.DataTypeID);
            var result = new MedianamikControl(pDALMedianamikControl.MedianamikControlID
                                               , pDALMedianamikControl.FullName
                                               , datatype)
                             {
                                Name = pDALMedianamikControl.Name,
                                MaySpecifyWidth = pDALMedianamikControl.MaySpecifyWidth ,
                                MaySpecifyHeight = pDALMedianamikControl.MaySpecifyHeight ,
                                DefaultWidth= Unit.Parse(pDALMedianamikControl.DefaultWidth ),
                                DefaultHeight = pDALMedianamikControl.DefaultHeight ,
                                MaySpecifyValidationExpression = pDALMedianamikControl.MaySpecifyValidationExpression ,
                                MaySpecifyLength = pDALMedianamikControl.MaySpecifyLength ,
                                DefaultMaxLength = pDALMedianamikControl.DefaultLength ,
                                MayBeRequired = pDALMedianamikControl.MayBeRequired ,
                                MayBeUnique = pDALMedianamikControl.MayBeUnique  
                             };

            return result;

        }
    }
}
